extends Container

const maxCardCount = 4
var CardLib = []
var gwide = 30
var ghigh = 25

func _ready() -> void:
	set_mouse_filter(0)
	pass 

func _process(delta: float) -> void:
	pass
	
func __Set_box_size(__size:Vector2):
	size = __size
	
func __ReSet_box_size():
	if CardLib.is_empty():
		__Set_box_size(Vector2.ZERO)
		return
	var csize = CardLib[0].size
	var wid = CardLib.size() * (csize.x + 30) + gwide
	var hig = csize.y + ghigh
	__Set_box_size(Vector2(wid,hig))
	
func __Card_should__chaged():
	for i in CardLib:
		var n_pos = CardLib.find(i)
		i.call("__change_pos",self,i.pos,n_pos) #需要实现改变位置时播放的动画
		i.pos = n_pos
		i.select = false
			
func __Card_put():
	for i in CardLib:
		if i.justInsert:
			i.call("__add_in_box",self,i.pos) #需要实现添加到盒子里播放的动画
			i.justInsert = false
			continue
		i.call("__put_in_box",self,i.pos) #需要卡牌自己决定自己的位置

func __Insert_Card(card) -> bool:
	card.justInsert = true
	CardLib.sort_custom(func (a,b): #如果相等，就把新的放后面（false）,级别越高越靠前
		if(a.level == b.level):
			if(a.justInsert):
				return false
			elif(b.justInsert):
				return true
		return a.level > b.level
		)
	card.pos = CardLib.find(card)
	card.candrag = false
	card.in_box = true
	gwide = card.size.x/(4)
	ghigh = card.size.y/10
	__Card_should__chaged()
	__Card_put()
	return true

func __Add_Card_node(card) -> bool:
	if (CardLib.size()>=maxCardCount):
		return false
	CardLib.append(card)
	add_child(card)
	return __Insert_Card(card)

func __Remove_Card_node(card):
	if(CardLib.is_empty()):
		return [false,"not card could be delete!"]
	var index = CardLib.find(card)
	if(index < 0):
		return [false,"can't find this card!"]
	CardLib[index].in_box = false
	CardLib[index].candrag = true
	var cardd = CardLib.pop_at(index)
	remove_child(cardd)
	if(CardLib.is_empty()):
		return [true,cardd]
	else:
		__Card_should__chaged()
		return [true,cardd]

func __Can_insert():
	if CardLib.size()>=maxCardCount:
		return false
	return true
	
func _on_mouse_entered() -> void:
	var now_node = __BaseFunc.now_draging_node
	now_node.in_other_box = self

func _on_mouse_exited() -> void:
	pass

func __Card_change_box(n_box,t_Card):
	if n_box == self:
		return [false,"same"]
	if not n_box.__Can_insert():
		return [false,"Can't put more"]
	var carr = __Remove_Card_node(t_Card)
	if not carr[0]:
		return carr
	n_box.__Add_Card_node(t_Card)
	t_Card.in_other_box = null
	return [true,carr]

func _on_area_2d_area_entered(area:Area2D) -> void:
	# print("Area.parent:",area.get_parent(),"self:",self)
	if area.get_parent() == __BaseFunc.now_draging_node:
		_on_mouse_entered()

func _on_area_2d_area_exited(area:Area2D) -> void:
	if area.get_parent() == __BaseFunc.now_draging_node:
		_on_mouse_exited()
